#include <iostream>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>

void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt = 1;
    while(true)
    {
        snprintf(buffer,sizeof buffer,"I am child: pid: %d, cnt = %d",getpid(),cnt);
        write(wfd,buffer,strlen(buffer));
        sleep(1);
        cnt++;
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        int n = read(rfd,buffer,sizeof(buffer) -1);
        if(n > 0)
        {
            buffer[n]=0;
            std::cout << "child say :" << buffer << std::endl;
        }
        break;
    }
}

int main()
{
    // 1、创建管道
    int fds[2] = {0}; // fds[0]:读端  fds[1]:写端
    int n = pipe(fds);
    if (n < 0)
    {
        std::cout << "pipe error" << std::endl;
    }
    std::cout << "fds[0]:" << fds[0] << std::endl;
    std::cout << "fds[1]:" << fds[1] << std::endl;

    // 2、创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        //3、关闭不需要读写端，形成通信信道
        //子进程进行写，关闭读端
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);   
    }

    // 3、关闭不需要读写端，形成通信信道
    // 父进程进行读，关闭写端
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);
    int status;
    int ret = waitpid(id,&status,0);
    if(ret > 0)
    {
        printf("exit code: %d , exit signal: %d\n",(status>>8)&0xff,(status)&0x7f);
        sleep(5);
    }
    return 0;
}